"""
金叉：2，死叉：-2  向上：1  向下：-1
支持重复计算，但是要指定timekey，只能向前重复计算
"""
class cross2:
    def __init__(self,a,b,isreverse=False):
        self.timekey=None
        self.his=[]
        self.a=a
        self.b=b
        if isreverse:
            self.oncalc=self.oncalc_True
        else:
            self.oncalc = self.oncalc_False
    def oncalc_False(self,c,timekey=None):
        rst=0
        if c is not None:
            if timekey   is not None:
                if timekey==self.timekey:
                    self.his.pop()
            if self.his:
                if c>self.a:
                    if self.his[-1]<=self.a:
                        rst=2
                elif c<self.b:
                    if self.his[-1]>=self.b:
                        rst=-2
            self.timekey=timekey
            self.his.append(c)
            while len(self.his)>2:
                self.his.pop(0)
        return rst
    def oncalc_True(self,c,timekey=None):
        rst=0
        if c is not None:
            if timekey   is not None:
                if timekey==self.timekey:
                    self.his.pop()
            if self.his:
                if self.his[-1] >= self.a:
                    if c<self.a:
                        rst=-2
                elif self.his[-1]<=self.b:
                    if c>self.b:
                        rst=2
            self.timekey=timekey
            self.his.append(c)
            while len(self.his)>2:
                self.his.pop(0)
        return rst


if __name__ == '__main__':
    from jili.core import load, save
    from research.calcor.calcors_graph import graph_calcor
    k1m = load(r"D:\data\future_k1m_tq\TA005\TA005_20200102.pkl")
    from research.calcor.dim2.cross import cross
    cross0=cross()
    cc = [{'calc_cmd': 'ta', 'cmd': 'EMA', 'out': ['ema30'], 'input': {'price': 'close'}, 'arg': {'timeperiod': 30},
           'batch': 30},
          {'calc_cmd': 'ta', 'cmd': 'EMA', 'out': ['ema10'], 'input': {'price': 'close'}, 'arg': {'timeperiod': 10},
           'batch': 10},
          {'calc_cmd': 'function', 'function': cross0.oncalc, 'out': 'cross0', 'input': ["ema10", "ema30","timekey"]}]
    c = graph_calcor(cc)
    k1ms=k1m[:32]
    for t in k1ms:
        t = c.onbar(t)
    print(t)
    t1 = k1m[32]
    t1["timekey"]=t["timekey"]
    t1=c.onbar(t1)
    print(t1)
    print("end")